package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Pattern;

/*
* 联讯接口
* */
@Slf4j
public class Plugin_ECARD_P019 implements ChannelService {

    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }

    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {

        try {
            String AccountVal = String.valueOf(data.get("AccountVal"));

            String type = accountType(AccountVal);
            if(type.equals("false")){
                return ChannelResult.error("充值号码异常");
            }
            long timestamp = System.currentTimeMillis();
            LinkedHashMap<String, String> params = new LinkedHashMap<>();
            params.put("account",apiConfig.getString("accInfo"));
            params.put("cc",apiConfig.getString("partnerNum"));
            params.put("time",String.valueOf(timestamp));
            params.put("csc",String.valueOf(data.get("SUPProductId")));
            params.put("style",type);//充值账号类型 1: QQ号 6：腾讯手机号充值（理解为微信号）  11: 手机号
            params.put("ra",AccountVal);
            params.put("pon",String.valueOf(data.get("ChannelOrderCode")));

            String secretKey = apiConfig.getString("secretKey");
            String sign = generateSignature(params, secretKey);
            params.put("sign",sign);
            String submitUrl = apiConfig.getString("SubmitUrl");

            String res = HttpTool.HttpPost(submitUrl, params);
            JSONObject reqParams = JSONObject.parseObject(res);
            String code = reqParams.getString("code");
            String msg = reqParams.getString("msg");

            if (code.equals("1")) {
                return ChannelResult.success("充值成功");
            }
            if(code.equals("100")){
                return ChannelResult.IN_PROCESS("充值中");
            }
            return ChannelResult.FAILED("充值失败##"+msg);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("联讯提交订单接口错误：",e);
            return  ChannelResult.error("联讯提交订单接口错误");
        }
    }

    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {

        try {
            long timestamp = System.currentTimeMillis();
            LinkedHashMap<String, String> queryParams = new LinkedHashMap<>();
            queryParams.put("account",apiConfig.getString("accInfo"));
            queryParams.put("cc",apiConfig.getString("partnerNum"));
            queryParams.put("time",String.valueOf(timestamp));
            queryParams.put("pon",String.valueOf(data.get("ChannelOrderCode")));

            String secretKey = apiConfig.getString("secretKey");
            String sign = generateSignature(queryParams, secretKey);
            String queryUrl = apiConfig.getString("QueryUrl");
            queryParams.put("sign",sign);

            String res = HttpTool.HttpPost(queryUrl,queryParams);
            JSONObject reqParams = JSONObject.parseObject(res);
            String code = reqParams.getString("code");
            String msg = reqParams.getString("msg");

            if (code.equals("1")) {
                return ChannelResult.success("充值成功");
            }
            if(code.equals("100")){
                return ChannelResult.IN_PROCESS("充值中");
            }
            return ChannelResult.FAILED("充值失败##"+msg);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("联讯查询订单接口错误：",e);
            return  ChannelResult.error("联讯查询订单接口错误");
        }
    }


    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");
    }

    public static String accountType(String input) {
        final String PHONE_REGEX = "^1[0-9]{10}$";
        final String WECHAT_REGEX = "^[a-zA-Z0-9_]{5,16}$";
        final String QQ_REGEX = "^[1-9]\\d{4,10}$";

        if (Pattern.matches(PHONE_REGEX,input)){
            return "11";
        }else if (Pattern.matches(QQ_REGEX,input)){
            return "1";
        }else if (Pattern.matches(WECHAT_REGEX,input)){
            return "6";
        }else{
            return "false";
        }
    }
    public static String generateSignature(LinkedHashMap<String, String> params, String privateKey) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(entry.getValue());
        }
        sb.append(privateKey);

        String signString = sb.toString();
        System.out.println("排序"+signString);
        return md5(signString).toUpperCase();
    }

    private static String md5(String input) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] inputBytes = input.getBytes();
            byte[] hashBytes = messageDigest.digest(inputBytes);

            StringBuilder sb = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    sb.append('0');
                }
                sb.append(hex);
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }


}
